package xyz.jiang.gateway.filter;

import cn.hutool.core.util.StrUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import xyz.jiang.common.grace.result.GraceJSONResult;
import xyz.jiang.common.grace.result.ResponseStatusEnum;
import xyz.jiang.common.utils.RedisUtils;
import xyz.jiang.common.utils.TokenUtils;
import xyz.jiang.gateway.utils.PathWhiteListChecker;

import java.util.List;

import static xyz.jiang.common.constants.TokenConstants.TOKEN_EXPIRE_TIME;
import static xyz.jiang.common.constants.TokenConstants.TOKEN_PREFIX;

@Data
@Slf4j
@Component
public class TokenFilter implements GlobalFilter, Ordered {

    private List<String> whiteList = List.of(
        "/auth/passport/*"
    );

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().value();
        boolean allowed = PathWhiteListChecker.isAllowed(path);
        if (!allowed) {
            String token = TokenUtils.getToken(request);
            if (StrUtil.isBlank(token)) {
                return GraceJSONResult.renderErrorMsg(exchange, ResponseStatusEnum.UN_LOGIN);
            }
            if (!RedisUtils.exists(TOKEN_PREFIX + token)) {
                return GraceJSONResult.renderErrorMsg(exchange, ResponseStatusEnum.TICKET_INVALID);
            }
            // 刷新token的过期时间
            RedisUtils.setExpireSeconds(TOKEN_PREFIX + token, TOKEN_EXPIRE_TIME);
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
